home *** CD-ROM | disk | FTP | other *** search
/ Nebula 1 / Nebula One.iso / Financial / USDebtWatch / unix-version / tm_to_time.c < prev    next >
C/C++ Source or Header  |  1995-06-12  |  1KB  |  55 lines

  1. #include <sys/types.h>
  2. #include <sys/time.h>
  3.  
  4. /* Return 1 if `y' is a leap year, 0 otherwise.
  5.  */
  6.  
  7. static int leap (y) int y; {
  8.     y += 1900;
  9.     if (y % 400 == 0)
  10.     return (1);
  11.     if (y % 100 == 0)
  12.     return (0);
  13.     return (y % 4 == 0);
  14. }
  15.  
  16. /* Return the number of days between Jan 1, 1970 and the given
  17.  * broken-down time.
  18.  */
  19.  
  20. static int ndays (p) struct tm *p; {
  21.     register n = p->tm_mday;
  22.     register m, y;
  23.     register char *md = "\37\34\37\36\37\36\37\37\36\37\36\37";
  24.  
  25.     for (y = 70; y < p->tm_year; ++y) {
  26.     n += 365;
  27.     if (leap (y)) ++n;
  28.     }
  29.     for (m = 0; m < p->tm_mon; ++m)
  30.     n += md[m] + (m == 1 && leap (y));
  31.     return (n);
  32. }
  33.  
  34. /* Convert a broken-down time (such as returned by localtime())
  35.  * back into a `time_t'.
  36.  */
  37.  
  38. time_t tm_to_time (tp) struct tm *tp; {
  39.     register int m1, m2;
  40.     time_t t;
  41.     struct tm otm;
  42.  
  43.     t = (ndays (tp) - 1) * 86400L + tp->tm_hour * 3600L
  44.     + tp->tm_min * 60 + tp->tm_sec;
  45.     /*
  46.      * Now the hard part -- correct for the time zone:
  47.      */
  48.     otm = *tp;
  49.     tp = localtime (&t);
  50.     m1 = tp->tm_hour * 60 + tp->tm_min;
  51.     m2 = otm.tm_hour * 60 + otm.tm_min;
  52.     t -= ((m1 - m2 + 720 + 1440) % 1440 - 720) * 60L;
  53.     return (t);
  54. }
  55.